package com.rxt.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.rxt.common.constant.RedisConstants;
import com.rxt.model.domain.FBankUser;
import com.rxt.model.dto.UUserDto;
import com.rxt.util.BankThreadLocal;
import com.rxt.util.BaseContext;
import com.rxt.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
public class BankHandlerInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    public BankHandlerInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("BankHandlerInterceptor - url: {}, method: {}", request.getRequestURI(), request.getMethod());
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }
        String token = request.getHeader(JwtUtils.TOKEN);
        log.info("token - {}", token);
        if (!StrUtil.isEmptyIfStr(token)) { // token存在
            // 从token中解析出用户id
            String username = Objects.requireNonNull(JwtUtils.get("username", token)).toString();
            // 从 redis 中获取用户信息
            String userKey = "BankUser_" + username;
            String userJson = stringRedisTemplate.opsForValue().get(userKey);
            if (!StrUtil.isEmptyIfStr(userJson)) { // 成功得到用户信息
                FBankUser fBankUser = JSON.parseObject(userJson, FBankUser.class);
                // 将用户信息保存到ThreadLocal中去
                BankThreadLocal.set(fBankUser);
                // 刷新redis中的用户信息
                stringRedisTemplate.expire(userKey, RedisConstants.USER_KEY_TTL, TimeUnit.MINUTES);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BankThreadLocal.remove();
    }
}
